/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package MaterialPack;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import EntityGameObject.*;
import Supporter.GlobalVariables;
import Supporter.ImageSupporter;
import javax.microedition.lcdui.game.Sprite;

import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @return the Emotion
 */
/**
 *
 * @author Van persie
 */
public class PetInstance extends MaterialObject {

    Pet pet = null;
    Animation currentSprite = null;
    Animation prevSprite = null;
    Animation NormalSprite = null;
    Animation WaitSprite = null;
    Image Tongue = null;
    //Animation Status = null;
    Animation SadFace = null;
    Animation HappyFace = null;
    Animation TiredFace = null;
    Animation StatusFull = null;
    int current = -1;
    int state = 0;
    int mode = -1;
    int decrStatus;
    int decrEmotion;
//    private int Status;
//    private int Emotion;
    private int MaxEmotion;
    private int MaxStatus;
    private int AvgEmotion;
    private int AvgStatus;
    long LastPlay;
    long LastFeed;
    ContextDialog[] AdvBubbles = null;
    ContextDialog[] DisBubbles = null;
    ContextDialog[] ExcBubbles = null;
    int AdvBub = 0;
    int DisBub = 0;
    int ExcBub = 0;
    int clock = 0;
    boolean isPlaying = false;
    private InfoPanel output = null;

    public PetInstance(int x, int y, int wid, int hei, Pet pascal, boolean isSprite) {

        super.GetGraphicsInfo(x, y, wid, hei);


        MaxStatus = 2000;
        MaxEmotion = 1000;
        AvgStatus = 80;
        AvgEmotion = 700;



        // WaitSprite = LoadSprite(pathPhoto, wid, hei, 1);
        ImageSupporter imsp = new ImageSupporter();
        isPlaying = isSprite;
        pet = pascal;
        if (!isSprite) {
            Vector temp = new Vector();
            temp.addElement(imsp.getImage("/open-mouth.png"));
            temp.addElement(imsp.getImage("/close-mouth.png"));

            Tongue = ImageSupporter.transparent(imsp.getImage("/tongue.png"));
            WaitSprite = new Animation(wid, hei, temp);
            currentSprite = WaitSprite;
        } else {
            SadFace = new Animation(4, 1, wid, hei, "/petboring.png");
            HappyFace = new Animation(3, 1, wid, hei, "/Happy.png");

            StatusFull = new Animation(4, 1, wid, hei, "/Full.png");
            StatusFull.setWarp(false);

            TiredFace = new Animation(3, 1, wid, hei, "/Hungry.png");
            NormalSprite = new Animation(3, 1, wid, hei, "/Normal.png");

            currentSprite = NormalSprite;

            if (pet.getStamina() <= 0) {
                //pet.setIsTired(false);
                pet.setIsFull(false);
                currentSprite = SadFace;
            } else if (pet.getStamina() < pet.getMaxStamina() / 3) {
                pet.setIsTired(true);
                currentSprite = TiredFace;
            }
            if (pet.getEmotion() <= 0) {
                pet.setIsHappy(false);
                currentSprite = SadFace;
            }
            pet.setIsHappy(true);
            
        }




        PrepareBubble();


        isVisible = true;
    }

    public void AddEXP(int a) {
        pet.AddAttributes(Pet.EXP, a);
        if (pet.GetAttributes(Pet.EXP) + a >= 100) {
            output.setText("OH! good ");
            GenerateBubble("Level Up", 100, 90, 80, 2);
        }
        //String text =  (a>0):("+ "+ a +"EXP")? ("- " + a + "EXP");
        if (a > 0) {
            GenerateBubble("+" + a + "EXP", 60, 60, 50, 0);
        } else {
            GenerateBubble(a + "EXP", 60, 60, 50, 1);
        }
    }

    public void AddItem(PetItem item) {
        //for(int i = 0; i < items.size(); i++)
        //    listItem.addElement(items.elementAt(i));
        pet.getListItems().addElement(item);

        pet.AddAttributes(Pet.MONEY, -item.getPrice());
        pet.AddAttributes(Pet.EXP, item.getIncrEXP());
        pet.AddAttributes(Pet.POINTS, item.getIncrPoints());
        pet.AddAttributes(Pet.SPEED, item.getIncrSpeed());
        pet.AddAttributes(Pet.TONGUELEN, item.getIncrTongueLen());
    }

    public void GenerateBubble(String text, int wid, int hei, int cooldown, int type) {
//        System.out.println(x);
//        System.out.println(y);
        int px = xPos + GlobalVariables.myRandom.nextInt() % (width / 2) - width / 8;
        int py = yPos - GlobalVariables.myRandom.nextInt() % (height / 2) - width / 8;
        switch (type) {
            case 0:
                AdvBubbles[AdvBub].SetAnchor(ContextDialog.HORIZON_MIDDLE, ContextDialog.VERTICAL_MIDDLE);
                AdvBubbles[AdvBub].Show(text, px, py, wid, hei, cooldown, 1);
                if (AdvBub < AdvBubbles.length - 1) {
                    AdvBub++;
                }
                break;
            case 1:
                DisBubbles[DisBub].SetAnchor(ContextDialog.HORIZON_MIDDLE, ContextDialog.VERTICAL_MIDDLE);
                DisBubbles[DisBub].Show(text, px, py, wid, hei, cooldown, 1);
                if (DisBub < DisBubbles.length - 1) {
                    DisBub++;
                }
                break;
            case 2:
                px = xPos + GlobalVariables.myRandom.nextInt() % (width / 4) - width / 8;
                py = yPos - GlobalVariables.myRandom.nextInt() % (height / 4) - width / 8;
                ExcBubbles[ExcBub].SetAnchor(ContextDialog.HORIZON_MIDDLE, ContextDialog.VERTICAL_MIDDLE);
                ExcBubbles[ExcBub].Show(text, px, py, wid, hei, cooldown, 1);
                if (ExcBub < ExcBubbles.length - 1) {
                    ExcBub++;
                }
                break;
        }

    }

    public void PrepareBubble() {

        ImageSupporter imSpp = new ImageSupporter();

        AdvBubbles = new ContextDialog[10];
        Image temp = ImageSupporter.transparent(ImageSupporter.alphaBlend(imSpp.getImage("/Bubble.png")));
        for (int i = 0; i < AdvBubbles.length; i++) {
            AdvBubbles[i] = new ContextDialog(temp);
        }
        AdvBub = 0;

        DisBubbles = new ContextDialog[5];
        temp = ImageSupporter.transparent(ImageSupporter.alphaBlend(imSpp.getImage("/WarningBubble.png")));
        for (int i = 0; i < DisBubbles.length; i++) {
            DisBubbles[i] = new ContextDialog(temp);
        }
        DisBub = 0;

        ExcBubbles = new ContextDialog[5];
        temp = ImageSupporter.transparent(ImageSupporter.alphaBlend(imSpp.getImage("/ExcilentBubble.png")));
        for (int i = 0; i < ExcBubbles.length; i++) {
            ExcBubbles[i] = new ContextDialog(temp);
        }
        ExcBub = 0;


    }

    public Sprite LoadSprite(String pathImg, int widframe, int heiframe, int n) {
        ImageSupporter imgSupp = new ImageSupporter();
        Image temp = imgSupp.getImage(pathImg);
        temp = ImageSupporter.scaleImage(temp, widframe * n, heiframe);
        temp = ImageSupporter.transparent(temp);

        Sprite spr = new Sprite(temp, widframe, heiframe);
        return spr;
    }

    public void Feed(PetItem item) {


        // pet.setStatus(getStatus() + item.getkCal());
        pet.setStamina(pet.getStamina() + item.getkCal() / 100);
        if (!pet.getIsTired()) {
            pet.setEmotion(pet.getEmotion() + 50);
        } else {
            GenerateBubble("+" + Integer.toString(item.getkCal() / 100) + "Health", 60, 60, 50, 0);
            pet.setEmotion(pet.getEmotion() - item.getkCal() / 100);
            //GenerateBubble("+0 EXP",60, 60, 50,0);

            //GenerateBubble("+" + Integer.toString(item.getkCal()) + " Cal",70, 60, 50,0);
        }

        if (pet.getStatus() > getAvgStatus()) {
            decrEmotion = 2;
        }

//        if(getStatus() > getMaxStatus())
//        {
//            pet.setIsTired(true);
//            if(currentSprite != TiredFace)
//                currentSprite = TiredFace;
//            
//            GenerateBubble("-" + Integer.toString(5*item.getIncrEXP()) + "EXP",60, 60, 50, 1);
//            GenerateBubble("I'm full!", 70, 60, 50,1);            
//            AddEXP(-5*item.getIncrEXP());
//            String []text = {"Can't eat more","Plz tap me!"};
//            output.setText(text);
//            
//        } else 
        GenerateBubble("+" + Integer.toString(item.getIncrEXP()) + "EXP", 60, 60, 50, 0);
        GenerateBubble("+" + Integer.toString(item.getkCal()) + "regen", 70, 60, 50, 0);
        AddEXP(1);


        pet.setIsFull(true);
        if (pet.isIsHappy() && !pet.getIsTired()) {
            if (getStamina() > getAvgStatus() && pet.getEmotion() > getAvgEmotion()) {
                if (currentSprite != HappyFace) {
                    currentSprite = HappyFace;
                }
                //GenerateBubble("Critical!", 80, 80, 70,2);
                GenerateBubble("+5EXp", 60, 60, 70, 2);
                AddEXP(5);
                String[] text = {"Oh yeah!", "Wonderfull"};
                output.setText(text);
            } else {
                output.setText("");
            }
//                 else if(currentSprite != StatusFull && pet.getEmotion() < getAvgEmotion() )
//                 {
//                     prevSprite = StatusFull;
//                     output.setText("");
//                 }
        }
        prevSprite = currentSprite;
        currentSprite = StatusFull;

//             if(pet.getEmotion() > getMaxEmotion())    // neu dang tired --> chuyen Exp sang relax = -= Emotion
//             {
//                GenerateBubble("+"+ Integer.toString(item.getIncrEXP()) + "Relax", 60, 60, 50,0);
//                
//                GenerateBubble("+0 EXP",60, 60, 50,0);
//                 
//                GenerateBubble("+" + Integer.toString(item.getkCal()) + " Cal",70, 60, 50,0);
//              
//                pet.setEmotion(pet.getEmotion() - item.getIncrEXP());
//                
//             }else 
//                 {
//                        GenerateBubble("+" + Integer.toString(item.getIncrEXP()) + " EXP",  60, 60, 50,0);
//                        GenerateBubble("+" + Integer.toString(item.getkCal()) + " Cal", 70, 60, 50,0);
//                        AddEXP(1);
//                 }

    }

    public void Play() {
        pet.setEmotion(pet.getEmotion() + 80);
        if (decrEmotion > getAvgEmotion()) {
            decrEmotion = 2;
        }


        if (pet.getEmotion() > getMaxEmotion()) {

            pet.setIsTired(true);
            if (currentSprite != TiredFace) {
                currentSprite = TiredFace;
            }


            GenerateBubble("-15EXP", 60, 60, 50, 1);
            GenerateBubble("-10Sta", 60, 60, 50, 1);
            GenerateBubble("I'm tired!", 70, 60, 50, 1);
            AddEXP(-15);
            pet.setStamina(pet.getStamina() - 10);
            String[] text = {"Can't play more", "Give more food!"};
            output.setText(text);
            System.out.println("descr Emotion");
            if (pet.getStamina() < pet.getMaxStamina() / 3 || pet.getEmotion() >= getMaxEmotion()) {
                pet.setIsTired(true);
                currentSprite = TiredFace;
            }

        } else {
            pet.setIsHappy(true);
            decrEmotion = 1;
            if (!pet.getIsTired()) {
                if (pet.getEmotion() > getAvgEmotion() /*&& pet.getStamina() >= pet.getMaxStamina()*/) {
                    if (currentSprite != HappyFace) {
                        currentSprite = HappyFace;
                    }
                    //GenerateBubble("Critical!", 100, 80, 70, 2);
                    GenerateBubble("+10EXp", 60, 60, 70, 2);
                    AddEXP(10);
                    output.setText("Oh yeah!Wonderfull");
                } else if (currentSprite != StatusFull && currentSprite != HappyFace) {
                    //currentSprite = StatusFull;
                    output.setText("");
                }
            }
            AddEXP(1);

        }

        LastPlay = System.currentTimeMillis();
    }

    public void Update() {



        if (pet.getIsTired() && pet.getStamina() > getMaxStamina()/3 && getEmotion()<getMaxEmotion() && currentSprite != StatusFull) {
            //pet.setStatus(getAvgStatus() / 2);
            pet.setEmotion(getMaxEmotion() / 2);
            pet.setIsTired(false);
            currentSprite = NormalSprite;
            decrEmotion=1;
            System.out.println("dec: "+decrEmotion);
        }
        if (currentSprite == HappyFace && pet.getEmotion() < getAvgEmotion() && currentSprite != StatusFull) {
            currentSprite = NormalSprite;
        }


        if (pet.getEmotion() <= getMaxEmotion() / 3) {
            pet.setIsHappy(false);
            decrEmotion = 1;
            if (currentSprite != SadFace && currentSprite != TiredFace && currentSprite != StatusFull) {
                // pet.setEmotion(Pet.EMOTION_SAD);
                currentSprite = SadFace;
                output.setText("Play with me ~~!");
                System.out.println("dec: "+decrEmotion);
                if (pet.getEmotion() <= 0) 
                      decrEmotion = 0;
                   
                   else 
                    decrEmotion = 1;
                System.out.println("dec: "+decrEmotion);
            }
            
        } else {
            
            if (pet.getEmotion() < getMaxEmotion() / 4 && currentSprite != StatusFull) {
                currentSprite = NormalSprite;
                output.setText("");
            }
            System.out.println("dec: "+decrEmotion);
        }
        pet.setEmotion(pet.getEmotion() - decrEmotion);
        UpdateAdvBubble();
        UpdateDisBubble();
        UpdateEcxBubble();


        if (clock == 0) {
            //current = (current + 1)%currentSprite.getFrameSequenceLength();
            //currentSprite.setFrame(current);
            //if( currentSprite.next())
            if (currentSprite.next() && prevSprite != null) {
                currentSprite = prevSprite;
            }

            pet.setStamina(pet.getStamina() + 1);
            if (pet.getIsTired() || pet.isIsHappy() == false) {
                AddEXP(-1);
            }
        }

        clock = (clock + 1) % 10;
        //      System.out.println(pet.getStatus());
        //      System.out.println(pet.getEmotion());


    }

    public void UpdateDisBubble() {
        if (DisBubbles != null) {
            for (int i = 0; i < DisBub; i++) {
                if (DisBubbles[i].MyUpdate()) {
                    ContextDialog temp = DisBubbles[i];
                    temp.isVisible = false;
                    DisBubbles[i] = DisBubbles[DisBub - 1];
                    DisBubbles[DisBub - 1] = temp;
                    DisBub--;
                }
            }
        }
    }

    public void UpdateEcxBubble() {
        if (ExcBubbles != null) {
            for (int i = 0; i < ExcBub; i++) {
                if (ExcBubbles[i].MyUpdate()) {
                    ContextDialog temp = ExcBubbles[i];
                    temp.isVisible = false;
                    ExcBubbles[i] = ExcBubbles[ExcBub - 1];
                    ExcBubbles[ExcBub - 1] = temp;
                    ExcBub--;
                }
            }
        }
    }

    public void UpdateAdvBubble() {
        if (AdvBubbles != null) {
            for (int i = 0; i < AdvBub; i++) {
                if (AdvBubbles[i].MyUpdate()) {
                    ContextDialog temp = AdvBubbles[i];
                    temp.isVisible = false;
                    AdvBubbles[i] = AdvBubbles[AdvBub - 1];
                    AdvBubbles[AdvBub - 1] = temp;
                    AdvBub--;
                }
            }
        }
    }

    public void paint(Graphics g) {
        if (isVisible) {
            //g.drawImage(background, getxPos(), getyPos(), Graphics.TOP | Graphics.LEFT);

            //currentSprite.setPosition(xPos, yPos);

            //currentSprite.paint(g);
            g.drawImage(currentSprite.GetCurrentFrame(), xPos, yPos, Graphics.HCENTER | Graphics.BOTTOM);
            if (!isPlaying && Tongue != null) {
                int heiTong = pet.getTongueLen();
                heiTong*=2;
                g.drawImage(ImageSupporter.scaleImage(Tongue, width / 4, heiTong), xPos - width / 4, yPos - (height + heiTong) + height / 4, Graphics.TOP | Graphics.LEFT);
            }


            if (AdvBubbles != null) {
                for (int i = 0; i < AdvBub; i++) {
                    AdvBubbles[i].paint(g);
                }
            }
            if (DisBubbles != null) {
                for (int i = 0; i < DisBub; i++) {
                    DisBubbles[i].paint(g);
                }
            }
            if (ExcBubbles != null) {
                for (int i = 0; i < ExcBub; i++) {
                    ExcBubbles[i].paint(g);
                }
            }
            // AdvBubbles.paint(g);
        }
    }

    public boolean isContained(int x, int y) {
        if (x > getxPos() - width / 2 && x < (getxPos() + getWidth() / 2) && y > getyPos() - height && y < (getyPos())) {
            return true;
        }
        return false;
    }

    public boolean Press(int x, int y) {
        if (isContained(x, y)) {
            if (isPlaying) {
                Play();
            } else {
                currentSprite.next();
                Tongue = null;
                state = 1;
                return true;
            }
        }
        return false;
    }

    public boolean Release(int x, int y) {
        if (state != 0) {
            // current = (current + 1)%currentSprite.getFrameSequenceLength();
            // currentSprite.setFrame(current);
            currentSprite.next();
            state = 0;
            return true;
        }
        return false;
    }

    public void UseItem(PetItem item) {
    }

    public void AddAttributes(int AttType, int Increment) {
        pet.AddAttributes(AttType, Increment);
    }

    public int GetAttributes(int AttType) {
        return pet.GetAttributes(AttType);
    }

    public void SetAttributes(int AttType, int Increment) {
        pet.SetAttributes(AttType, Increment);
    }

    /**
     * @return the speech
     */
    public int getSpeed() {
        return pet.getSpeech();
    }

    /**
     * @param speech the speech to set
     */
    public void setSpeed(int speech) {
        pet.setSpeech(speech);
    }

    public int getStamina() {
        return pet.getStamina();
    }

    /**
     * @param speech the speech to set
     */
    public void setStamina(int stamina) {
        pet.setStamina(stamina);
    }

    /**
     * @return the tongueLen
     */
    public int getTongueLen() {
        return pet.getTongueLen();
    }

    /**
     * @param tongueLen the tongueLen to set
     */
    public void setTongueLen(int tongueLen) {
        pet.setTongueLen(tongueLen);
    }

    /**
     * @return the listItem
     */
    public Vector getListItem() {
        return pet.getListItems();
    }

    /**
     * @param listItem the listItem to set
     */
    public void setListItem(Vector listItem) {
        pet.setListItems(listItem);
    }

    /**
     * @return the Status
     */
    public int getStatus() {
        return pet.getStatus();
    }

    public int getMaxStamina() {
        return pet.getMaxStamina();
    }

    public int getEmotion() {
        return pet.getEmotion();
    }

    /**
     * @return the MaxEmotion
     */
    public int getMaxEmotion() {
        return MaxEmotion;
    }

    /**
     * @param MaxEmotion the MaxEmotion to set
     */
    public void setMaxEmotion(int MaxEmotion) {
        this.MaxEmotion = MaxEmotion;
    }

    /**
     * @return the MaxStatus
     */
    public int getMaxStatus() {
        return MaxStatus;
    }

    /**
     * @param MaxStatus the MaxStatus to set
     */
    public void setMaxStatus(int MaxStatus) {
        this.MaxStatus = MaxStatus;
    }

    /**
     * @return the AvgEmotion
     */
    public int getAvgEmotion() {
        return AvgEmotion;
    }

    /**
     * @param AvgEmotion the AvgEmotion to set
     */
    public void setAvgEmotion(int AvgEmotion) {
        this.AvgEmotion = AvgEmotion;
    }

    /**
     * @return the AvgStatus
     */
    public int getAvgStatus() {
        return AvgStatus;
    }

    /**
     * @param AvgStatus the AvgStatus to set
     */
    public void setAvgStatus(int AvgStatus) {
        this.AvgStatus = AvgStatus;
    }

    /**
     * @return the output
     */
    public InfoPanel getOutput() {
        return output;
    }

    /**
     * @param output the output to set
     */
    public void setOutput(InfoPanel output) {
        this.output = output;
    }

    public void SetAgility(int val) {
        pet.setAgility(val);
    }

    public int GetAgility() {
        return pet.getAgility();
    }

    public void SetStrength(int val) {
        pet.setStrength(val);
    }

    public int GetStrength() {
        return pet.getStrength();
    }
    /**
     * @param pet.getStatus()the pet.getStatus()to set
     */
}
/**
 * @return the MaxEmotion
 */
